package com.xipu.yygh.manage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xipu.yygh.common.exception.YyghException;
import com.xipu.yygh.manage.repository.DepartmentRepository;
import com.xipu.yygh.manage.service.DepartmentService;
import com.xipu.yygh.model.hosp.Department;
import com.xipu.yygh.vo.hosp.DepartmentQueryVo;
import com.xipu.yygh.vo.hosp.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * description: 部门Service
 * @author: gql
 * @date: 2022/05
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {

    /**
     * 部门表(Mongo)
     */
    @Autowired
    private DepartmentRepository departmentRepository;

    /**
     * 上传科室
     * @param map 医院传过来的科室信息
     */
    @Override
    public void saveDepartment(Map<String, Object> map) {
        Department department = JSONObject.parseObject(JSONObject.toJSONString(map), Department.class);
        if (StringUtils.isEmpty(department)) {
            throw new YyghException(20001, "上传数据异常!");
        } else {
            // 查询科室是否存在(根据医院编号和科室编号)
            Department existDepartment =
                    this.departmentRepository.findByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());
            if (StringUtils.isEmpty(existDepartment)) {
                // 添加
                department.setCreateTime(new Date());
            } else {
                // 修改
                department.setId(existDepartment.getId());
            }
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }
    }

    /**
     * 分页查询科室信息
     * @param page 当前页
     * @param limit 每页记录数
     * @param departmentQueryVo 查询条件
     * @return 分页数据
     */
    @Override
    public Page<Department> findPageDepartment(int page, int limit, DepartmentQueryVo departmentQueryVo) {
        // 1.设置排序规则
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");

        // 2.设置分页数据
        Pageable pageable = PageRequest.of(page - 1, limit, sort);

        // 3.条件匹配器
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        // 4.将departmentQueryVo转换为department
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);
        department.setIsDeleted(0);

        // 5.封装查询条件
        Example<Department> example = Example.of(department, matcher);

        // 6.执行查询
        return departmentRepository.findAll(example, pageable);
    }

    /**
     * 根据医院编号和部门编号删除
     * @param hoscode 医院编号
     * @param depcode 部门编号
     */
    @Override
    public void departmentRemove(String hoscode, String depcode) {
        // 先根据hoscode和depcode查询到科室信息
        Department department = departmentRepository.findByHoscodeAndDepcode(hoscode, depcode);

        // 如果不为空才根据id删除
        if (!StringUtils.isEmpty(department)) {
            this.departmentRepository.deleteById(department.getId());
        }
    }

    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        // 1.根据hoscode查询医院科室列表
        List<Department> deptList = this.departmentRepository.findDepartmentByHoscode(hoscode);

        // 2.根据大科室进行分组,key:大科室编号；value:大科室中的记录
        Map<String, List<Department>> bigDepartmentMap =
                deptList.stream().collect(Collectors.groupingBy(Department::getBigcode));

        List<DepartmentVo> resultList = new ArrayList<>();

        // 3.封装大科室和小科室
        for (Map.Entry<String, List<Department>> entry : bigDepartmentMap.entrySet()) {
            // 大科室编号
            String key = entry.getKey();
            // 每个大科室的小科室集合
            List<Department> value = entry.getValue();

            DepartmentVo departmentVo = new DepartmentVo();
            // 设置depcode、depname
            departmentVo.setDepcode(key);
            departmentVo.setDepname(value.get(0).getBigname());
            // 设置List<DepartmentVo> children
            List<DepartmentVo> children = new ArrayList<>();
            for (Department department : value) {
                DepartmentVo deprtmentVoTemp = new DepartmentVo();
                deprtmentVoTemp.setDepcode(department.getDepcode());
                deprtmentVoTemp.setDepname(department.getDepname());
                children.add(deprtmentVoTemp);
            }
            departmentVo.setChildren(children);

            resultList.add(departmentVo);
        }
        return resultList;
    }

    @Override
    public String getDepName(String hoscode, String depcode) {
        Department department = this.departmentRepository.findDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if (StringUtils.isEmpty(department)) {
            return null;
        } else {
            return department.getDepname();
        }

    }

    @Override
    public Department getDepartment(String hoscode, String depcode) {
        return this.departmentRepository.findDepartmentByHoscodeAndDepcode(hoscode,depcode);
    }
}
